<template>
  <div>
    <n-space vertical size="large">
      <n-card title="基本信息">
        <n-form :model="formValue" label-placement="left" label-width="100">
          <n-form-item label="用户名">
            <n-input v-model:value="formValue.username" disabled />
          </n-form-item>
          <n-form-item label="昵称">
            <n-input v-model:value="formValue.nickname" />
          </n-form-item>
          <n-form-item label="手机号">
            <n-input v-model:value="formValue.phone" />
          </n-form-item>
          <n-form-item label="邮箱">
            <n-input v-model:value="formValue.email" />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="updateBasicInfo">保存</n-button>
          </n-form-item>
        </n-form>
      </n-card>

      <n-card title="修改密码">
        <n-form :model="passwordForm" label-placement="left" label-width="100">
          <n-form-item label="原密码">
            <n-input v-model:value="passwordForm.oldPassword" type="password" />
          </n-form-item>
          <n-form-item label="新密码">
            <n-input v-model:value="passwordForm.newPassword" type="password" />
          </n-form-item>
          <n-form-item label="确认密码">
            <n-input v-model:value="passwordForm.confirmPassword" type="password" />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="changePassword">修改密码</n-button>
          </n-form-item>
        </n-form>
      </n-card>
    </n-space>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getUserDetail, updateUser, changePassword as changeUserPassword } from '@/api/user'

const userStore = useUserStore()

const formValue = reactive({
  username: '',
  nickname: '',
  phone: '',
  email: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const loadUserInfo = async () => {
  try {
    const res = await getUserDetail(userStore.userId)
    Object.assign(formValue, res.data)
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }
}

const updateBasicInfo = async () => {
  try {
    await updateUser(userStore.userId, formValue)
    window.$message?.success('更新成功')
    userStore.nickname = formValue.nickname
  } catch (error) {
    console.error('更新用户信息失败:', error)
  }
}

const changePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    window.$message?.error('两次输入的密码不一致')
    return
  }

  try {
    await changeUserPassword(userStore.userId, {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    window.$message?.success('密码修改成功，请重新登录')
    userStore.logout()
    window.location.href = '/login'
  } catch (error) {
    console.error('修改密码失败:', error)
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

